package com.woorigil.social.controller.member;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.woorigil.social.domain.member.Member;
import com.woorigil.social.domain.member.MemberDao;

@Controller
public class LoginController {
	@Autowired MemberDao memberDao;
	
	@RequestMapping("member/loginForm")
	public ModelAndView loginForm(){
		ModelAndView mav = new ModelAndView("member/loginForm");
		return mav;
	}
	
	@RequestMapping("/member/login")
	public ModelAndView login(String id, String password, HttpSession session){
		ModelAndView mav = null;
		
		Member member = memberDao.selectById(id);
		
		System.out.println(id+password);
		if(member != null) {
			if(member.getPassword().equals(password)) {
				mav = new ModelAndView(new RedirectView("/main.html"));
				session.setAttribute("member", member);
			}
			else {
				System.out.println("패스워드가 맞지 않습니다.");
				mav = new ModelAndView("member/loginForm","error_message","패스워드가 틀렸습니다.");
			}
		}else
		{
			new IllegalArgumentException("존재하지 않는 아이디 입니다.");
			mav = new ModelAndView("member/loginForm","error_message","존재하지 않는 아이디 입니다.");
		}
		
		return mav;
	}
	@RequestMapping("/member/logout")
	public ModelAndView logout(HttpSession session){
		ModelAndView mav = null;
		Member member = (Member)session.getAttribute("member");
		if(member != null){
			mav = new ModelAndView(new RedirectView("/main.html"));
			session.invalidate();
		}else
		{
			mav = new ModelAndView("member/loginForm","error_message","로그인후 이용하세요.");
		}
		return mav;
	}
	
}
